package com.zhuhjay.common.redis.util;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import static com.zhuhjay.common.base.constant.CacheConstant.ID_WORKER_PREFIX;

/**
 * id生成器
 * @author ZhuHJay
 * @date 2023/2/25 11:12
 */
public class RedisIdWorker {

    /** 时间戳开始时间 **/
    private static final long BEGIN_TIME;
    /** 偏移量 **/
    private static final long COUNT_BITS = 32L;

    static {
        LocalDateTime localDateTime = LocalDateTime.of(2023, 1, 1, 0, 0, 0);
        BEGIN_TIME = localDateTime.toEpochSecond(ZoneOffset.UTC);
    }

    /**
     * 获取唯一id
     * @param businessKey 业务标识
     * @return id
     */
    @SuppressWarnings("all")
    public static long nextId(String businessKey) {
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 计算时间戳
        long timestamp = nowSecond - BEGIN_TIME;
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // key自增
        String key = ID_WORKER_PREFIX + businessKey + ":" + format;
        long count = RedisUtils.increment(key);
        // 设置过期时间
        if (count == 1) {
            RedisUtils.setKeyExpireShort(key);
        }
        return timestamp << COUNT_BITS | count;
    }
}
